package CI.aufgabe2.cip.mynodes;

import CI.aufgabe2.cip.SymbolTable;
import CI.aufgabe2.cip.base.AbstractDescr;

public class MyIfNode extends MyAbstractNode {

	private static final long serialVersionUID = 1L;

	MyAbstractNode condition, elsePart;
	MyStatementSequenceNode thenPart;

	public MyIfNode() {
		condition = null;
		thenPart = null;
		elsePart = null;
	};

	public MyIfNode(MyAbstractNode fe, MyStatementSequenceNode fst1,
			MyAbstractNode fst2) {
		condition = fe;
		thenPart = fst1;
		elsePart = fst2;
	};

	public void setCondition(MyAbstractNode fe) {
		condition = fe;
	};

	public void setThenPart(MyStatementSequenceNode fst1) {
		thenPart = fst1;
	};

	public void setElsePart(MyAbstractNode fst2) {
		elsePart = fst2;
	};

	public MyAbstractNode getCondition() {
		return condition;
	};

	public MyStatementSequenceNode getThenPart() {
		return thenPart;
	};

	public MyAbstractNode getElsePart() {
		return elsePart;
	};

	public void print() {
		trace("IfNode ");
		condition.print();
		if (thenPart != null)
			thenPart.print();
		if (elsePart != null)
			elsePart.print();
		unindent();
	};

	public void compileElseIf(SymbolTable sym, int end) {
		condition.compile(sym);
		write("BF, " + labelCount);
		thenPart.compile(sym);
		write("JMP, " + end);
		if (elsePart != null) {
			if (elsePart instanceof MyIfNode) {
				write("LABEL, " + MyAbstractNode.getNextLabelNumber());
				((MyIfNode) elsePart).compileElseIf(sym, end);
			} else {
				write("LABEL, " + MyAbstractNode.getNextLabelNumber());
				elsePart.compile(sym);
			}
		}
	}

	public int getCount() {
		if (elsePart != null) {
			if (elsePart instanceof MyIfNode) {
				return ((MyIfNode) elsePart).getCount() + 1;
			}else{
				return 1;
			}
		}
		return 0;
	}

	public AbstractDescr compile(SymbolTable sym) {
		condition.compile(sym);
		write("BF, " + labelCount);
		thenPart.compile(sym);
		int end = (MyAbstractNode.labelCount + getCount());
		write("JMP, " + end);
		if (elsePart != null) {
			write("LABEL, " + MyAbstractNode.getNextLabelNumber());
			if (elsePart instanceof MyIfNode) {
				((MyIfNode) elsePart).compileElseIf(sym, end);
			} else {
				elsePart.compile(sym);
			}
		}
		write("LABEL, " + MyAbstractNode.getNextLabelNumber());
		return null;
	}

}
